package ctrl

import (
	"fmt"
	"im/model"
	"im/service"
	"im/util"
	"math/rand"
	"net/http"
)

var userService service.UserService

// userLogin 用户登录
func UserLogin(w http.ResponseWriter, r *http.Request) {
    err := r.ParseForm()
    if err != nil {
        util.Resp(w, -1, err.Error(), nil)
    }
	mobile := r.PostForm.Get("mobile")
	password := r.PostForm.Get("password")
    user, err := userService.Login(mobile, password)
    if err != nil {
        util.Resp(w, -1, err.Error(), nil)
	} else {
		util.Resp(w, 0, "", user)
	}
}

// 用户注册
func UserRegister(w http.ResponseWriter, r *http.Request) {
    err := r.ParseForm()
    if err != nil {
        util.Resp(w, -1, err.Error(), nil)
    }
	mobile := r.PostForm.Get("mobile")
	plainpwd := r.PostForm.Get("password")
	nickname := fmt.Sprintf ("user%06d", rand.Int31n(1000000))
	avatar := ""
	sex := model.SEX_MAN
    user, err := userService.Register(mobile, plainpwd, nickname, avatar, sex)
    if err != nil {
        util.Resp(w, -1, err.Error(), nil)
    } else {
        util.Resp(w, 0, "suc", user)
    }
}
